/**
 * financial-purchase.js - 理财产品购买相关功能模块
 * 处理产品购买、收益计算等功能
 */

/**
 * 更新预期收益
 */
function updateExpectedReturn() {
  if (!currentProductDetail) {
    return;
  }
  
  const amountInput = document.getElementById('purchase-amount');
  const amount = parseFloat(amountInput.value);
  
  if (isNaN(amount) || amount <= 0) {
    document.getElementById('expected-return').textContent = '¥0.00';
    return;
  }
  
  // 验证金额范围
  if (amount < currentProductDetail.minAmount) {
    document.getElementById('expected-return').textContent = '金额过小';
    return;
  }
  
  if (currentProductDetail.maxAmount && amount > currentProductDetail.maxAmount) {
    document.getElementById('expected-return').textContent = '金额过大';
    return;
  }
  
  // 计算预期收益 = 投资金额 * 年化收益率 * 投资期限 / 365
  const profit = amount * currentProductDetail.expectedReturn / 100 * currentProductDetail.duration / 365;
  
  document.getElementById('expected-return').textContent = '¥' + profit.toFixed(2);
}

/**
 * 购买产品
 */
function purchaseProduct() {
  if (!currentProductDetail) {
    Toast.error('产品信息不完整，请刷新后重试');
    return;
  }
  
  const amountInput = document.getElementById('purchase-amount');
  const amount = parseFloat(amountInput.value);
  
  // 验证金额
  if (isNaN(amount) || amount <= 0) {
    Toast.error('请输入有效的投资金额');
    return;
  }
  
  if (amount < currentProductDetail.minAmount) {
    Toast.error(`投资金额不能低于${currentProductDetail.minAmount.toLocaleString()}元`);
    return;
  }
  
  if (currentProductDetail.maxAmount && amount > currentProductDetail.maxAmount) {
    Toast.error(`投资金额不能超过${currentProductDetail.maxAmount.toLocaleString()}元`);
    return;
  }
  
  // 验证协议同意
  if (!document.getElementById('purchase-agreement').checked) {
    Toast.error('请阅读并同意协议');
    return;
  }
  
  // 构建请求数据
  const purchaseData = {
    productId: currentProductDetail.id,
    amount: amount,
    paymentPassword: '123456' // 正式环境应提示用户输入支付密码
  };
  
  // 调用购买API
  ApiService.post('/api/finance/product/purchase', purchaseData)
    .then(response => {
      if (response.code === 0 && response.data) {
        const order = response.data;
        
        // 更新成功页面信息
        document.getElementById('success-order-no').textContent = order.orderNo;
        document.getElementById('success-product-name').textContent = order.productName;
        document.getElementById('success-amount').textContent = '¥' + order.amount.toLocaleString();
        document.getElementById('success-profit').textContent = '¥' + order.expectedProfit.toLocaleString();
        
        // 格式化日期
        const valueTime = new Date(order.valueTime).toLocaleDateString();
        const dueTime = new Date(order.dueTime).toLocaleDateString();
        document.getElementById('success-value-date').textContent = valueTime;
        document.getElementById('success-due-date').textContent = dueTime;
        
        // 关闭产品详情模态框
        document.getElementById('product-detail-modal').style.display = 'none';
        
        // 显示购买成功模态框
        document.getElementById('purchase-success-modal').style.display = 'block';
        
        // 重新加载摘要数据
        loadSummary();
      } else {
        throw new Error(response.message || '购买失败');
      }
    })
    .catch(error => {
      console.error('购买产品失败:', error);
      Toast.error('购买失败: ' + error.message);
    });
}

/**
 * 格式化日期字符串
 * @param {string} dateString - 日期字符串
 * @param {boolean} withTime - 是否包含时间
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(dateString, withTime = false) {
  if (!dateString) return '-';
  
  const date = new Date(dateString);
  
  if (isNaN(date.getTime())) {
    return dateString;
  }
  
  if (withTime) {
    return date.toLocaleString();
  } else {
    return date.toLocaleDateString();
  }
}
